import {
  divide3Float3Fixed,
  divide2Float2Fixed
} from './NumberChange';

import {
  dateNumFormat,
  generateDate
} from './commonFunc';

let data = new Object();

/**
 * 导出送货单
 * @param {*} form 
 * @param {*} table 
 * @param {*} totalAmount 
 */
function exportDeliveryExcel(form, table, totalAmount) {
  data = new Object();

  // 全边框
  const border = { // 设置边框
    top: { style: 'medium' },
    bottom: { style: 'medium' },
    left: { style: 'medium' },
    right: { style: 'medium' }
  }

  /**
   * 标题栏样式
   */
  const headStyle = {
    font: {
      name: "宋体",
      sz: 20,
      bold: true
    },
    alignment: {
      horizontal: "center",
      vertical: "center",
      indent: 0
    }
  };

  /**
   * 单元项样式
   */
  const itemStyle = {
    border: border,
    alignment: {
      vertical: "center",
    }
  }


  /**
   * form 数据样式
  */
  const formStyle = {
    font: {
      name: "宋体",
    },
  };


  /**
   * 标题的Item 数据样式
   */
  const titleItemStyle = Object.assign({
    alignment: {
      horizontal: "center",
      vertical: "center",
      indent: 0
    }
  }, formStyle)

  const formStyleLeft = Object.assign({
    alignment: {
      horizontal: "left",
      vertical: "center",
      indent: 0
    }
  }, formStyle);

  const formStyleRight = Object.assign({
    alignment: {
      horizontal: "right",
      vertical: "center",
      indent: 0
    }
  }, formStyle);

  const theadStyle = {
    font: {
      name: "宋体",
      bold: true
    },
    alignment: {
      horizontal: "center",
      vertical: "center",
      indent: 0
    },
    border
  }

  /**
   * 数据
   */
  data = {
    '!ref': 'A1:K30',
    A1: { v: '深圳市鸿惠丰包装制品有限公司', s: headStyle },
    A2: { v: `地址：布吉雪岗南路97号峰华工业区二栋一楼`, s: titleItemStyle },
    A3: { v: `电话：13828784612   传真：28794545`, s: titleItemStyle },
    A4: { v: `客户：${form.clientName}`, s: formStyleLeft },
    A5: { v: `电话：${form.clientPhone}`, s: formStyleLeft },
    A6: { v: `地址：${form.deliveryAddress}`, s: formStyleLeft },
    D4: { v: `送货单`, s: headStyle },
    G4: { v: `送货单号：${form.deliveryNumber}`, s: formStyleRight },
    G5: { v: `送货日期：${form.deliveryDate}`, s: formStyleRight },
    G6: { v: `货币：${form.currency}`, s: formStyleRight },
    A7: { v: `客户PO`, s: theadStyle },
    B7: { v: `客方货号`, s: theadStyle },
    C7: { v: `盒式`, s: theadStyle },
    D7: { v: `纸质`, s: theadStyle },
    E7: { v: `规格`, s: theadStyle },
    F7: { v: `数量`, s: theadStyle },
    G7: { v: `单价`, s: theadStyle },
    H7: { v: `金额`, s: theadStyle },
    I7: { v: `备注/标注`, s: theadStyle },
  };

  // 当前的行号
  let row = 8;

  for (let i = 0; i < table.length; i++) {
    data[gridName('A', row)] = { v: table[i].po, s: itemStyle };
    data[gridName('B', row)] = { v: table[i].goodsNumber, s: itemStyle };
    data[gridName('C', row)] = { v: table[i].goodsType, s: itemStyle };
    data[gridName('D', row)] = { v: table[i].quality, s: itemStyle };
    data[gridName('E', row)] = { v: table[i].size, s: itemStyle };
    data[gridName('F', row)] = { v: table[i].quantity, s: itemStyle };
    data[gridName('G', row)] = { v: divide3Float3Fixed(table[i].price).toString(), s: itemStyle };
    data[gridName('H', row)] = { v: divide3Float3Fixed(table[i].amount).toString(), s: itemStyle };
    data[gridName('I', row)] = { v: table[i].remark, s: itemStyle };
    row++;
  }

  // 补齐没有的行
  for (; row < 18; row++) {
    data[gridName('A', row)] = { v: '', s: itemStyle };
    data[gridName('B', row)] = { v: '', s: itemStyle };
    data[gridName('C', row)] = { v: '', s: itemStyle };
    data[gridName('D', row)] = { v: '', s: itemStyle };
    data[gridName('E', row)] = { v: '', s: itemStyle };
    data[gridName('F', row)] = { v: '', s: itemStyle };
    data[gridName('G', row)] = { v: '', s: itemStyle };
    data[gridName('H', row)] = { v: '', s: itemStyle };
    data[gridName('I', row)] = { v: '', s: itemStyle };
  }

  data[gridName('G', row)] = {
    v: `总金额（${form.currency}）：${divide3Float3Fixed(totalAmount).toString()}`, s: {
      font: {
        name: "宋体",
        bold: true,
      },
      alignment: {
        vertical: "center"
      },
      border
    }
  };

  data[gridName('H', row)] = {
    v: '',
    s: {
      border: {
        bottom: { style: 'medium' },
      }
    }
  }

  data[gridName('I', row)] = {
    v: '',
    s: {
      border: {
        bottom: { style: 'medium' },
        right: { style: 'medium' },
      }
    }
  }

  row++;
  data[gridName('A', row)] = {
    v: `送货车牌：${form.plateNumber}`
  };

  data[gridName('C', row)] = {
    v: `审核人：${form.reviewer}`
  };

  data[gridName('F', row)] = {
    v: `用户签名及盖章：____________________`,
    s: {
      alignment: {
        horizontal: "right",
        indent: 0
      },
    }
  };

  const merge = [{
    s: { r: 0, c: 0 },
    e: { r: 0, c: 8 }
  }, {
    s: { r: 1, c: 0 },
    e: { r: 1, c: 8 }
  }, {
    s: { r: 2, c: 0 },
    e: { r: 2, c: 8 }
  }, {
    s: { r: 3, c: 0 },
    e: { r: 3, c: 2 }
  }, {
    s: { r: 4, c: 0 },
    e: { r: 4, c: 2 }
  }, {
    s: { r: 5, c: 0 },
    e: { r: 5, c: 4 }
  }, {
    s: { r: 3, c: 3 },
    e: { r: 4, c: 5 }
  }, {
    s: { r: 3, c: 6 },
    e: { r: 3, c: 8 }
  }, {
    s: { r: 4, c: 6 },
    e: { r: 4, c: 8 }
  }, {
    s: { r: 5, c: 6 },
    e: { r: 5, c: 8 }
  }, {
    s: { r: 17, c: 6 },
    e: { r: 17, c: 8 }
  }, {
    s: { r: 18, c: 0 },
    e: { r: 18, c: 1 }
  }, {
    s: { r: 18, c: 2 },
    e: { r: 18, c: 4 }
  }, {
    s: { r: 18, c: 5 },
    e: { r: 18, c: 8 }
  },
  ];

  data['!merges'] = merge;
  const cols = [
    { wpx: 110 },
    { wpx: 100 },
    { wpx: 50 },
    { wpx: 50 },
    { wpx: 110 },
    { wpx: 55 },
    { wpx: 55 },
    { wpx: 75 },
    { wpx: 165 }
  ];

  const rows = [{ hpx: 45 }];
  for (let i = 1; i < 18; i++) {
    rows.push({ hpx: 20 });
  }
  rows.push({ hpx: 30 });

  data['!cols'] = cols;
  data['!rows'] = rows;

  var wb = {
    SheetNames: ['Sheet1'],
    Sheets: {
      Sheet1: data
    }
  };

  var tmpDown = new Blob([
    s2ab(
      // 这里的数据是用来定义导出的格式类型
      XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
      })
    )
  ], {
    type: ""
  });
  saveAs(tmpDown, `送货单-${form.clientName}-${form.deliveryNumber}.xlsx`);
}

/**
 * 导出月结单
 * @param {Array} tableData 
 * @param {Object} summary 
 */
function exportSummaryExcel(tableData, summary) {
  data = new Object();

  const date = generateDate();


  const headStyle = {
    font: {
      bold: true
    },

    border: { // 设置边框
      top: { style: 'thin' },
      bottom: { style: 'thin' },
      left: { style: 'thin' },
      right: { style: 'thin' }
    }
  };

  const itemStyle = {
    border: { // 设置边框
      top: { style: 'thin' },
      bottom: { style: 'thin' },
      left: { style: 'thin' },
      right: { style: 'thin' }
    }
  }

  data = {
    '!ref': 'A1:K100',
    A1: {
      v: '深圳市鸿惠丰包装制品有限公司',
      s: {
        font: {
          name: "宋体",
          sz: 24,
          bold: true,
        },
        alignment: {
          horizontal: "center",
          indent: 0
        }
      },
    },
    A2: {
      v: '地址：布吉雪岗南路97号峰华工业区二栋一楼',
      s: {
        alignment: {
          horizontal: "center",
          indent: 0
        }
      },
    },
    A3: {
      v: '电话：0755-28872173 28790073 ;  传真：28794545',
      s: {
        alignment: {
          horizontal: "center",
          indent: 0
        }
      },
    },
    A4: {
      v: '月结单',
      s: {
        font: {
          name: "宋体",
          sz: 20,
          bold: true,
        },
        alignment: {
          horizontal: "center",
          indent: 0
        }
      },
    },
    A5: { v: `客户名称：${summary.client}` },
    F5: { v: `制单日期：${date}` },

    A6: { v: '送货日期', s: headStyle },
    B6: { v: '送货单号', s: headStyle },
    C6: { v: '客户PO', s: headStyle },
    D6: { v: '客方货号', s: headStyle },
    E6: { v: '盒式', s: headStyle },
    F6: { v: '纸质', s: headStyle },
    G6: { v: '规格', s: headStyle },
    H6: { v: '数量', s: headStyle },
    I6: { v: '单价', s: headStyle },
    J6: { v: '金额', s: headStyle },
    K6: { v: '备注', s: headStyle },
  };

  // 当前的行号
  let row = 7;
  // 当前的列
  let column = 'A';



  for (let i = 0; i < tableData.length; i++) {
    data['A' + row.toString()] = { v: dateNumFormat(tableData[i].deliveryDate.toString()), s: itemStyle };
    data['B' + row.toString()] = { v: tableData[i].deliveryNumber.toString(), s: itemStyle };
    data['C' + row.toString()] = { v: tableData[i].po.toString(), s: itemStyle };
    data['D' + row.toString()] = { v: tableData[i].goodsNumber.toString(), s: itemStyle };
    data['E' + row.toString()] = { v: tableData[i].goodsType.toString(), s: itemStyle };
    data['F' + row.toString()] = { v: tableData[i].quality.toString(), s: itemStyle };
    data['G' + row.toString()] = { v: tableData[i].size.toString(), s: itemStyle };
    data['H' + row.toString()] = { v: tableData[i].quantity.toString(), s: itemStyle };
    data['I' + row.toString()] = { v: divide3Float3Fixed(tableData[i].price).toString(), s: itemStyle };
    data['J' + row.toString()] = { v: divide2Float2Fixed(tableData[i].amount / 10).toString(), s: itemStyle };
    data['K' + row.toString()] = { v: tableData[i].remark.toString(), s: itemStyle };
    row++;
  }

  data[gridName('A', row)] = {
    v: '总金额（RMB）：', s: {
      font: {
        name: "宋体",
        sz: 15,
        bold: true,
      },
      alignment: {
        horizontal: 'right'
      },
      border: { // 设置边框
        left: { style: 'thin' },
      }
    }
  };

  data[gridName('G', row)] = {
    v: summary.totalAmount, s: {
      font: {
        name: "宋体",
        sz: 15,
        bold: true,
      },
      alignment: {
        horizontal: 'right'
      },
      border: { // 设置边框
        left: { style: 'thin' },
      }
    }
  };

  data[gridName('K', row)] = {
    s: {
      border: { // 设置边框
        right: { style: 'thin' },
      }
    }
  }

  const summaryStyle = {
    font: {
      name: "宋体",
      sz: 15,
      bold: true,
    },
    alignment: {
      horizontal: 'center'
    },
    border: { // 设置边框
      top: { style: 'thin' },
      bottom: { style: 'thin' },
    }
  }

  data[gridName('A', row + 1)] = { v: '注：上述数据如有错误，请于10日内告知以便更正，否则将按此数请款，多谢合作！' };
  setRowStyle(row + 1, summaryStyle);

  data[gridName('A', row + 2)] = { v: summary.companyName + ' | 开户行：' + summary.bank, s: summaryStyle };
  setRowStyle(row + 2, summaryStyle);

  data[gridName('A', row + 3)] = { v: '账号： ' + summary.account, s: summaryStyle };
  setRowStyle(row + 3, summaryStyle);

  const merge = [{
    s: { r: 0, c: 0 },
    e: { r: 0, c: 10 }
  },
  {
    s: { r: 1, c: 0 },
    e: { r: 1, c: 10 }
  },
  {
    s: { r: 2, c: 0 },
    e: { r: 2, c: 10 }
  },
  {
    s: { r: 3, c: 0 },
    e: { r: 3, c: 10 }
  }, {
    s: { r: 4, c: 0 },
    e: { r: 4, c: 4 }
  }, {
    s: { r: 4, c: 5 },
    e: { r: 4, c: 10 }
  }, {
    s: { r: row - 1, c: 0 },
    e: { r: row - 1, c: 5 }
  }, {
    s: { r: row - 1, c: 6 },
    e: { r: row - 1, c: 10 }
  }, {
    s: { r: row, c: 0 },
    e: { r: row, c: 10 }
  }, {
    s: { r: row + 1, c: 0 },
    e: { r: row + 1, c: 10 }
  }, {
    s: { r: row + 2, c: 0 },
    e: { r: row + 2, c: 10 }
  },
  ];

  data['!merges'] = merge;

  const cols = [
    { wpx: 90 },
    { wpx: 100 },
    { wpx: 140 },
    { wpx: 130 },
    { wpx: 70 },
    { wpx: 70 },
    { wpx: 130 },
    { wpx: 80 },
    { wpx: 80 },
    { wpx: 90 },
    { wpx: 140 },
  ];

  data['!cols'] = cols;

  var wb = {
    SheetNames: ['Sheet1'],
    Sheets: {
      Sheet1: data
    }
  };

  var tmpDown = new Blob([
    s2ab(
      // 这里的数据是用来定义导出的格式类型
      XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'binary'
      })
    )
  ], {
    type: ""
  });
  saveAs(tmpDown, `${generateDate()}-${summary.client}.xlsx`);
}

function saveAs(obj, fileName) {
  var tmpa = document.createElement("a");
  tmpa.download = fileName || "下载";
  tmpa.href = URL.createObjectURL(obj);
  tmpa.click();
  setTimeout(function () {
    URL.revokeObjectURL(obj);
  }, 100);
}

function s2ab(s) {
  if (typeof ArrayBuffer !== 'undefined') {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) {
      view[i] = s.charCodeAt(i) & 0xFF;
    }
    return buf;
  } else {
    var buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) {
      buf[i] = s.charCodeAt(i) & 0xFF;
    }
    return buf;
  }
}

/**
 * 输入列和行，返回格子名
 * @param {string} column 
 * @param {number} row 
 */
function gridName(column, row) {
  return column + row.toString();
}

/**
 * 设置一行的样式
 * @param {number} row 要设置的行
 * @param {object} style 样式
 */
function setRowStyle(row, style) {
  data[gridName('A', row)] = Object.assign(data[gridName('A', row)] ?? {}, {
    s: style
  });
  data[gridName('B', row)] = Object.assign(data[gridName('B', row)] ?? {}, {
    s: style
  });
  data[gridName('C', row)] = Object.assign(data[gridName('C', row)] ?? {}, {
    s: style
  });
  data[gridName('D', row)] = Object.assign(data[gridName('D', row)] ?? {}, {
    s: style
  });
  data[gridName('E', row)] = Object.assign(data[gridName('E', row)] ?? {}, {
    s: style
  });
  data[gridName('F', row)] = Object.assign(data[gridName('F', row)] ?? {}, {
    s: style
  });
  data[gridName('G', row)] = Object.assign(data[gridName('G', row)] ?? {}, {
    s: style
  });
  data[gridName('H', row)] = Object.assign(data[gridName('H', row)] ?? {}, {
    s: style
  });
  data[gridName('I', row)] = Object.assign(data[gridName('I', row)] ?? {}, {
    s: style
  });
  data[gridName('J', row)] = Object.assign(data[gridName('J', row)] ?? {}, {
    s: style
  });
  data[gridName('K', row)] = Object.assign(data[gridName('K', row)] ?? {}, {
    s: style
  });
}

export {
  exportSummaryExcel,
  exportDeliveryExcel
};